import router from '@/router'
import store from '@/store'
import {getToken, setPreUrl, getRoleType} from '@/utils/token'

import user from '@/store/modules/user'
import {apiGetMenuList} from '@/api/login'

// Progress 进度条
import NProgress from 'nprogress'
// Progress 进度条样式
import 'nprogress/nprogress.css'

const whiteList = [
  '/login'
]
const permissionList = [
  '/basic/info/outsourcerPoint',
  '/basic/info/outsourcerPointRepairer',
  '/repairs/point/logistics',
  '/repairs/factory/repair',
  '/repairs/logistics',
  '/standby/grant',
  '/stock/good/repair/factory/detail',
  '/stock/good/repair/point/detail',
  '/stock/logistic',
  '/basic/changePwd'
]
var checkUrl = function (menuList, url) {
  if (menuList.id === null || menuList.id === undefined || menuList.children.size <= 0) {
    return false
  }
  if (menuList.path === url) {
    return true
  } else {
    for (let i in menuList.children) {
      if (checkUrl(menuList.children[i], url)) {
        return true
      }
    }
  }
  return false
}
router.beforeEach((to, from, next) => {
  // 开启Progress
  NProgress.start()
  // 判断是否有token
  if (getToken()) {
    if (to.path === '/login') {
      next({path: '/'})
    } else if (to.path === '/') {
      next()
    } else if (to.path === '/404') {
      next()
    } else if (to.path === '/basic/changePwd') {
      next()
    } else {
      // 判断当前用户信息是否存在
      if (store.getters.id === -1) {
        next({path: '/login'})
      } else {
        if (user.state.menuList !== null) {
          next()
        } else {
          apiGetMenuList().then(response => {
            let _menuListNew = response.data.menu
            if (to.path in permissionList) {
              if (to.path === '/repairs/factory/repair') {
                if (getRoleType() === '4') {
                  next()
                } else {
                  next({path: '/404'})
                }
              }
            } else if (checkUrl(_menuListNew, to.path)) {
              next()
            } else {
              next({path: '/404'})
            }
          }).catch(() => {
            // removeToken()
            // this.$router.push({path:'/login'})
          })
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (to.path !== '/404') {
        setPreUrl(to.path)
      }
      next({path: '/login'})
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
